package sort.impl;

import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;
import java.util.Stack;

public class QuickSorterNonRecursive extends AbstractQuickSorter {

    public QuickSorterNonRecursive() {
        super(SorterType.QUICK_NON_RECURSIVE);
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts, int left, int right) {
        Stack<Integer> S = new Stack<Integer>();
        S.push(left);
        S.push(right);
        while (!S.empty()) {
            right = S.pop();
            left = S.pop();
            if (right <= left) {
                continue;
            }
            int i = partition(tComparator, ts, left, right);
            if (i - left > right - i) {
                S.push(left);
                S.push(i - 1);
            }
            S.push(i + 1);
            S.push(right);
            if ((right - i) >= (i-left)){
                S.push(left);
                S.push(i - 1);
            }
        }
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size()-1);
    }
}

